package com.vcom.deploy.log;

import com.vcom.deploy.cmd.CmdThread;
import org.noear.solon.annotation.ServerEndpoint;
import org.noear.solon.core.message.Listener;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.Session;

import java.io.IOException;
import java.io.InputStream;

/**
 * 监听模式
 * 方便做会话的组织和收集，比如做聊天室，做应用推送等。
 */
@ServerEndpoint(path = "/ws/log")
public class LogWebSocketServer implements Listener {

    private Process process;
    private InputStream inputStream;
    private InputStream errorStream;

    @Override
    public void onOpen(Session session) {
        String app = session.param("app");
        String options = session.param("options");
        String logPath = LogConstant.linuxLogPathMap.get(app);
        String cmd = String.format("tail %s %s", options, logPath);
        try {
            String[] params = cmd.split(" ");
            process = new ProcessBuilder(params).start();
            inputStream = process.getInputStream();
            errorStream = process.getErrorStream();
            // 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
            CmdThread thread = new CmdThread(inputStream, errorStream, session);
            thread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(Session session, Message message) {
        session.send(message.bodyAsString());
    }

    @Override
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
        Listener.super.onError(session, error);
    }

    /**
     * WebSocket请求关闭
     */
    public void onClose(Session session) {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (errorStream != null) {
                errorStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (process != null) {
            process.destroy();
        }
        Listener.super.onClose(session);
    }

}
